from flask import Blueprint, request, jsonify
from models import db, Employee
import json

employee_bp = Blueprint('employee', __name__)

@employee_bp.route('/api/employees', methods=['GET'])
def get_employees():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    employees = Employee.query.paginate(page=page, per_page=per_page, error_out=False)
    return jsonify({
        'total': employees.total,
        'page': page,
        'per_page': per_page,
        'total_pages': employees.pages,
        'data': [employee.to_dict() for employee in employees.items]
    })

@employee_bp.route('/api/employees', methods=['POST'])
def create_employee():
    data = request.get_json()
    employee = Employee(**data)
    db.session.add(employee)
    db.session.commit()
    return jsonify({'message': '创建成功', 'id': employee.id}), 201

@employee_bp.route('/api/employees/<int:id>', methods=['PUT'])
def update_employee(id):
    employee = Employee.query.get_or_404(id)
    data = request.get_json()
    # 只更新普通字段，过滤掉一对多/多对多关系字段以及不应从前端更新的字段
    relation_fields = ['projects', 'work_experiences', 'educations']
    # 过滤掉不应从前端更新的字段
    data.pop('created_at', None)
    data.pop('updated_at', None)

    # 处理 language_level 字段，确保它是字符串存储
    if 'language_level' in data and isinstance(data['language_level'], list):
        try:
            data['language_level'] = json.dumps(data['language_level'])
        except TypeError:
            # 如果转换失败，设置为 None 或者空字符串，避免保存错误
            data['language_level'] = None # 或者 '''

    for key, value in data.items():
        if key in relation_fields:
            continue
        setattr(employee, key, value)
    db.session.commit()
    return jsonify({'message': '修改成功'})

@employee_bp.route('/api/employees/<int:id>', methods=['DELETE'])
def delete_employee(id):
    employee = Employee.query.get_or_404(id)
    db.session.delete(employee)
    db.session.commit()
    return jsonify({'message': '删除成功'})

@employee_bp.route('/api/employees/<int:id>', methods=['GET'])
def get_employee(id):
    employee = Employee.query.get_or_404(id)
    return jsonify(employee.to_dict()) 